package novel.front.novellist.task;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import novel.common.utils.EmojiConverterUtil;
import novel.common.utils.HttpClientUtil;
import novel.common.utils.OkttpUtil;
import novel.front.novellist.dao.AppsoMapper;
import novel.front.novellist.entity.Appso;
import novel.front.novellist.entity.Kuaixun;
import novel.front.novellist.entity.LiebaoApp;
import novel.front.novellist.service.KuaixunService;
import novel.front.novellist.service.LiebaoAppService;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Slf4j
@Component
public class SpriderUd {

    @Resource
    private LiebaoAppService liebaoAppService;


    @Resource
    private KuaixunService kuaixunService;

    @Resource
    private AppsoMapper appsoMapper;

    //    @Scheduled(cron = "* */1 * * * ?")
    @Scheduled(cron = "0 0 */1 * * ?")
    public void spirderTask() {
        try {
            zhixiaoSprider("https://sso.ifanr.com/api/v5/trochili/miniapp/limit=21");
        } catch (Exception e) {
            log.error("zhixiaoSprider error:", e.getMessage(), e);
        }

        try {
            kuaixun();
        } catch (Exception e) {
            log.error("kuaixun error:", e.getMessage(), e);
        }

        try {
            appso();
        } catch (Exception e) {
            log.error("appso error:", e.getMessage(), e);
        }

    }

    private void appso() {
        String url = "https://sso.ifanr.com/api/v5/wp/article/?post_type=app&limit=20&offset=0";
        String jsonStr = HttpClientUtil.doGet(url);
        JSONObject jsonObject = (JSONObject) JSONObject.parse(jsonStr);
        JSONArray jsonArray = JSONArray.parseArray(jsonObject.getString("objects"));
        for (int j = 0; j < jsonArray.size(); j++) {
            JSONObject obj = (JSONObject) jsonArray.get(j);
            Appso appso = JSON.toJavaObject(obj, Appso.class);
            Appso search = new Appso();
            search.setPost_id(appso.getPost_id());
            List<Appso> appsoList = appsoMapper.selectByExample(search);
            if (CollectionUtils.isEmpty(appsoList)) {
                try {
                    String time = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date((Long.parseLong(appso.getPublished_at()) * 1000)));
                    appso.setPublished_at(time);
                    String time2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date((Long.parseLong(appso.getUpdated_at()) * 1000)));
                    appso.setUpdated_at(time2);
                    appso.setPost_content(EmojiConverterUtil.emojiConvert1(appso.getPost_content()));
                    appso.setPost_title(EmojiConverterUtil.emojiConvert1(appso.getPost_title()));
                    appso.setPost_excerpt(EmojiConverterUtil.emojiConvert1(appso.getPost_excerpt()));
                    appso.setId(null);
                    appsoMapper.insertSelective(appso);
                } catch (Exception e) {
                    log.error("app so save {}", e.getMessage(), e);
                }
            } else {
                log.info("-----------------已存在-------------------");
            }
        }

    }

    private void kuaixun() {
        String url = "https://zhishuapi.aldwx.com/Main/action/Dashboard/Homepage/newsFlash";
        Kuaixun kuaixun;
        for (int i = 1; i < 3; i++) {
            System.out.println("page:" + i);
            String jsonStr = OkttpUtil.postData(url, i + "");
            JSONObject jsonObject = (JSONObject) JSONObject.parse(jsonStr);
            JSONArray jsonArray = JSONArray.parseArray(jsonObject.getString("data"));
            for (int j = 0; j < jsonArray.size(); j++) {
                JSONObject obj = (JSONObject) jsonArray.get(j);
                kuaixun = JSON.toJavaObject(obj, Kuaixun.class);
                kuaixun.setPublicshAt(obj.getString("publicsh_at"));
                kuaixun.setId(null);
                List<Kuaixun> list = kuaixunService.getList(kuaixun);
                if (CollectionUtils.isEmpty(list)) {
                    kuaixunService.save(kuaixun);
                }

            }
        }
    }

    // 知晓程序
    private void zhixiaoSprider(String url) {
        String jsonStr = HttpClientUtil.doGet(url);
        JSONObject jsonObject = (JSONObject) JSONObject.parse(jsonStr);
        String limit = ((JSONObject) JSONObject.parse(jsonObject.getString("meta"))).getString("limit");
        JSONArray jsonArray = JSONArray.parseArray(jsonObject.getString("objects"));

        List<LiebaoApp> liebaoJsonPojoList = new ArrayList<>();
        LiebaoApp liebao;
        for (int i = 0; i < jsonArray.size(); i++) {
            liebao = new LiebaoApp();
            JSONObject obj = (JSONObject) jsonArray.get(i);
            liebao.setAppId(Integer.parseInt(obj.getString("id")));
            liebao.setAppId(Integer.parseInt(obj.getString("id")));
            liebao.setAppSum(obj.getString("description"));
            liebao.setAppName(obj.getString("name"));
            LiebaoApp appByName = liebaoAppService.getAppByName(liebao.getAppName());
            if (appByName != null) {
                continue;
            }
            liebao.setAuthor("酷酷屋小程序");
            liebao.setHot(obj.getString("visit_amount"));
            liebao.setLogoUrl(((JSONObject) JSONObject.parse(obj.getString("icon"))).getString("image").substring(34));
            liebao.setQrUrl(((JSONObject) JSONObject.parse(obj.getString("qrcode"))).getString("image").substring(34));
            JSONArray screenshotArr = JSONArray.parseArray(obj.getString("screenshot"));
            String shotStr = "";
            for (int j = 0; j < screenshotArr.size(); j++) {
                JSONObject shotObj = (JSONObject) screenshotArr.get(j);
                shotStr += shotObj.getString("image") + ",";
            }
            liebao.setScrUrlsArr(shotStr.substring(0, shotStr.length() - 1));

            JSONArray tagArr = JSONArray.parseArray(obj.getString("tag"));
            String tagStr = "";
            for (int k = 0; k < tagArr.size(); k++) {
                JSONObject tagObj = (JSONObject) tagArr.get(k);
                tagStr += tagObj.getString("name") + ",";
            }
            liebao.setTagsArr(tagStr.substring(0, tagStr.length() - 1));
            liebao.setSourceId(2);
            liebao.setSourceUrl("minapp.com");
            liebao.setHomeType(3);
            liebaoJsonPojoList.add(liebao);
        }
        if (CollectionUtils.isEmpty(liebaoJsonPojoList)) {
            log.info("知晓无新增");
        } else {
            log.info("知晓新增：{}", liebaoJsonPojoList.size());
            liebaoAppService.saveAppList(liebaoJsonPojoList);
        }
    }

    public static String timeStamp2Date(String seconds, String format) {
        if (seconds == null || seconds.isEmpty() || seconds.equals("null")) {
            return "";
        }
        if (format == null || format.isEmpty()) {
            format = "yyyy-MM-dd HH:mm:ss";
        }
        SimpleDateFormat sdf = new SimpleDateFormat(format);
        return sdf.format(new Date(Long.valueOf(seconds + "000")));
    }

    public static void main(String[] args) {

    }
}
